<template>
  <div class="smart-plan-details">
    <common-table
      ref="commonTable"
      v-if="isInit"
      :biz-type="bizType"
      type="planDetails"
      :fields="fields"
      :list-data="listData"
      :total="total"
      :list-loading="loading"
      :operation="operation"
      :show-select-column="true"
      :storage-key="storageKey"
      @search="handleSearch"
    >
      <div slot="header_left">
        <el-radio-group v-model="jobStatus" @change="jobStatusChange">
          <el-radio-button label="0">{{ $t('task.taskTypes.planTask.toBeCreate') }}</el-radio-button>
          <el-radio-button label="1">{{ $t('common.base.usualStatus.hasCreated') }}</el-radio-button>
          <el-radio-button label="2">{{ $t('common.base.tip.createFail') }}</el-radio-button>
        </el-radio-group>
      </div>
      <div slot="actions" slot-scope="{ row }" v-if="showButton">
        <el-button type="text" @click="createNow(row)">{{ $t('task.taskTypes.planTask.createNow') }}</el-button>
        <el-button type="text" @click="changeTime(row)">{{ $t('task.taskTypes.planTask.changeTime') }}</el-button>
        <el-button type="text" @click="deletePlanJob(row)">{{ $t('common.base.delete') }}</el-button>
      </div>
    </common-table>
    <!-- start 预计创建时间 -->
    <change-time-dialog ref="changeTimeDialog" @planAdjustTimeSuccess="operateSuccess"/>
    <!-- end 预计创建时间 -->
  </div>
</template>

<script>
import CommonTable from '@src/modules/smartPlan/common/commonTable.vue'
import ChangeTimeDialog from './changeTimeDialog'
import { getTriggerFieldList, getPlanJobDetails, executePlanJob, removePlanJob } from '@src/modules/smartPlan/api/index.js'
import { handleOperation } from '@src/modules/smartPlan/util/index.js'
import { isArray } from 'pub-bbx-utils'
import { t } from '@src/locales'

export default {
  // 任务明细
  name: 'smart-plan-details',
  data() {
    return {
      isInit: false,
      jobStatus: 1,
      dynamicFields: [],
      listData: [],
      loading: false,
      total: 0,
    }
  },
  props: {
    bizType: {
      type: String,
      default: 'TASK'
    },
    planTypeId: {
      type: String,
      default: ''
    },
    planId: {
      type: String,
      default: ''
    },
    periodSetting: {
      type: Object,
      default: () => ({})
    },
    endSetting: {
      type: Object,
      default: () => ({})
    },
    allowEditSmartPlan: {
      type: Boolean,
      default: false
    },
  },
  computed: {
    storageKey() {
      return `smartPlanDetails_${this.bizType}_${this.jobStatus}`
    },
    fixedFields() {
      let fields = []
      if (this.bizType == 'TASK') {
        fields = [{
          displayName: t('common.label.serialNumber'),
          fieldName: 'bizNo',
          show: this.jobStatus == 1,
          sortId: this.jobStatus == 1 ? 1 : this.jobStatus == 2 ? 3 : 2
        }, {
          displayName: t('common.label.taskStatus'),
          fieldName: 'state',
          show: this.jobStatus == 1,
          sortId: this.jobStatus == 1 ? 2 : this.jobStatus == 2 ? 4 : 3
        }, {
          displayName: t('common.label.taskTemplate'),
          fieldName: 'planTypeName',
          show: true,
          sortId: this.jobStatus == 1 ? 3 : this.jobStatus == 2 ? 5 : 4
        }]
      } else if (this.bizType == 'EVENT') {
        fields = [{
          displayName: t('common.label.serialNumber'),
          fieldName: 'bizNo',
          show: this.jobStatus == 1,
          sortId: this.jobStatus == 1 ? 1 : this.jobStatus == 2 ? 3 : 2
        }, {
          displayName: t('common.event.eventState'),
          fieldName: 'state',
          show: this.jobStatus == 1,
          sortId: this.jobStatus == 1 ? 2 : this.jobStatus == 2 ? 4 : 3
        }, {
          displayName: t('common.event.eventType'),
          fieldName: 'planTypeName',
          show: true,
          sortId: this.jobStatus == 1 ? 3 : this.jobStatus == 2 ? 5 : 4
        }]
      } else if (this.bizType == 'PAAS') {
        fields = [{
          displayName: t('common.label.serialNumber'),
          fieldName: 'bizNo',
          show: this.jobStatus == 1,
          sortId: this.jobStatus == 1 ? 1 : this.jobStatus == 2 ? 3 : 2
        }, {
          displayName: t('common.label.status'),
          fieldName: 'status',
          show: this.jobStatus == 1,
          sortId: this.jobStatus == 1 ? 2 : this.jobStatus == 2 ? 4 : 3
        }, {
          displayName: t('common.label.type'),
          fieldName: 'planTypeName',
          show: true,
          sortId: this.jobStatus == 1 ? 3 : this.jobStatus == 2 ? 5 : 4
        }]
      } else if (this.bizType == 'ACTIVITY_RESEARCH') {
        fields = [{
          displayName: t('smartPlan.activityName'),
          fieldName: 'activitiesName',
          show: this.jobStatus == 1,
          sortId: this.jobStatus == 1 ? 1 : this.jobStatus == 2 ? 3 : 2
        }, {
          displayName: t('common.label.status'),
          fieldName: 'activitiesState',
          show: this.jobStatus == 1,
          sortId: this.jobStatus == 1 ? 2 : this.jobStatus == 2 ? 4 : 3
        }, {
          displayName: t('smartPlan.researchTemplate'),
          fieldName: 'satisfactionName',
          show: true,
          sortId: this.jobStatus == 1 ? 3 : this.jobStatus == 2 ? 5 : 4
        }]
      }
      if (this.jobStatus == 0) {
        fields.push({
          displayName: t('task.taskTypes.planTask.estimatedCreationTime'),
          fieldName: 'planTime',
          formType: 'datetime',
          show: true,
          sortId: 1
        })
      } else {
        if (this.jobStatus == 2) {
          fields.push({
            displayName: t('common.record.linkcOrder.failCause'),
            fieldName: 'errorMsg',
            show: true,
            sortId: 2
          })
        }
        fields.push({
          displayName: t('common.label.createTime'),
          fieldName: (this.bizType == 'PAAS' || this.jobStatus == 2) ? 'executeTime' : 'createTime',
          formType: 'datetime',
          show: true,
          sortId: this.jobStatus == 1 ? 4 : 1
        })
      }
      return fields.sort((a, b) => a.sortId - b.sortId).map(f => {
        f.isSystem = 1
        return f
      }).filter(f => f.show)
    },
    fields() {
      return this.fixedFields.concat(this.dynamicFields).sort((a, b) => a.sortId - b.sortId).map(item => {
        item.tableName = 'smartPlanDetails'
        return item
      })
    },
    showButton() {
      return this.jobStatus == 0 && this.listData.length && this.allowEditSmartPlan
    },
    operation() {
      if (this.showButton) {
        return {
          isShow: true,
          width: '220px'
        }
      }
      return {}
    }
  },
  async mounted() {
    await this.getFields()
    this.getList()
  },
  methods: {
    jobStatusChange() {
      this.$refs.commonTable.page = {
        pageNum: 1,
        pageSize: 10
      }
      this.$refs.commonTable.keyword = ''
      this.getList()
      this.$nextTick(() => {
        this.$refs.commonTable.buildColumns()
      })
    },
    handleSearch(params) {
      this.getList(params)
    },
    async getFields() {
      const res = await getTriggerFieldList({
        bizType: this.bizType,
        formId: this.planTypeId
      })
      this.isInit = true
      this.dynamicFields = res.data || []
    },
    buildParams() {
      return {
        keyword: '',
        pageNum: 1,
        pageSize: 10,
      }
    },
    getList(params) {
      const searchParams = {
        id: this.planId,
        jobStatus: this.jobStatus,
        ...this.buildParams(),
        ...params
      }
      this.loading = true
      getPlanJobDetails(searchParams).then(res => {
        this.loading = false
        this.listData = (res.data?.list || []).map(item => {
          try {
            item.bizVO = item.bizVO || {}
            if (this.jobStatus != 1) {
              for (let key in item.bizVO) {
                if (key.indexOf('field') > -1 && item.bizVO[key] && isArray(item.bizVO[key])) {
                  item.bizVO[key] = JSON.parse(item.bizVO[key][0])
                }
              }
              // 待创建和创建失败客户、产品取值处理
              if (item.planJobDetail?.param?.customer) {
                item.bizVO.customer = item.planJobDetail.param.customer
              }
              if (item.planJobDetail?.param?.product) {
                item.bizVO.product = item.planJobDetail.param.product
              }
            }
            // PAAS已创建取值处理
            if (this.jobStatus == 1 && this.bizType == 'PAAS') {
              item.bizVO.formValue = item.bizVO.formValue || {}
              item.bizVO = {
                ...item.bizVO,
                ...item.bizVO.formValue
              }
            }
            // 工单事件取值处理
            if (this.bizType == 'TASK' || this.bizType == 'EVENT') {
              item.bizVO = {
                ...item.bizVO,
                ...item.bizVO.attribute
              }
            }
          } catch (error) {
            console.error('handle planDetails data error', error)
          }
          
          return {
            ...item,
            ...item.bizVO,
          }
        })
        this.total = res.data?.total || 0
      })
    },
    operateSuccess() {
      this.$refs.commonTable.page = {
        pageNum: 1,
        pageSize: 10
      }
      this.$refs.commonTable.keyword = ''
      this.getList()
      this.$emit('updateDynamicInfo')
    },
    createNowSuccess() {
      this.operateSuccess()
      // 重复周期为动态周期时，过5s刷新一下数据
      if (this.periodSetting?.type == 'dynamic' && this.jobStatus == 0) {
        setTimeout(() => {
          this.getList()
        }, 5000)
      }
    },
    // 立即创建
    createNow(row) {
      handleOperation(
        executePlanJob,
        {
          id: this.planId,
          jobId: row.planJobDetail.id
        },
        t('smartPlan.tips.tip5'),
        this.createNowSuccess
      )
    },
    // 删除任务
    deletePlanJob(row) {
      handleOperation(
        removePlanJob,
        {
          id: this.planId,
          jobId: row.planJobDetail.id
        },
        t('smartPlan.tips.tip6'),
        this.operateSuccess
      )
    },
    // 打开调整预计创建时间弹窗
    changeTime(row) {
      row.planId = this.planId
      row.maxDate = this.endSetting?.specifyTime ?? row.planJobDetail?.jobConfig?.endTime
      this.$refs.changeTimeDialog.openDialog(row)
    },
  },
  components: {
    CommonTable,
    ChangeTimeDialog,
  }
}
</script>

<style lang="scss">
.smart-plan-details {
  .el-radio-button--small .el-radio-button__inner {
    background: #F5F8FA;
  }
}
</style>